package com.tool.controller;

import com.tool.server.Email;
import com.tool.util.Create;
import com.tool.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liuxuhuang
 * @Product IntelliJ IDEA
 * @Package com.tool.controller
 * @Title SendController
 * @Description:
 * @email liuxuhuang3970@qq.com
 * @date 2021/10/25 16:40
 */
@RestController
public class SendController {
    @Autowired
    private Email sendEmail;
    @Autowired
    private Create create;
    @Autowired
    private RedisUtil redisUtil;
    Logger logger = LoggerFactory.getLogger(SendController.class);

    @RequestMapping(value = "sendEmail", method = RequestMethod.POST)
    public Map sendEmailTo(@RequestBody Map map) {
        String address = map.get("email").toString();
        String code = create.createNumber(4);
        if (redisUtil.exists(address + "_Escort_Tool")) {
            redisUtil.delete(address + "_Escort_Tool");
        }
        boolean flag1 = redisUtil.set(address + "_Escort_Tool", code);
        boolean flag2 = sendEmail.snedEmail(address, "验证码验证", "验证码：" + String.valueOf(code));
        Map m = new HashMap();
        if (flag1 && flag2) {
            logger.warn("账号：" + address + ",发送邮件成功，验证码为：" + code);
            m.put("code", 200);
            m.put("msg", "发送成功");
            m.put("success", true);
        } else {
            logger.error("账号：" + address + ",发送邮件失败");
            m.put("code", 201);
            m.put("msg", "发送失败");
            m.put("success", false);
        }
        return m;
    }

    @RequestMapping(value = "validateCode", method = RequestMethod.POST)
    public Map validateCode(@RequestBody Map map) {
        String address = map.get("email").toString();
        String code = map.get("code").toString();
        Map m = new HashMap();
        if (redisUtil.exists(address + "_Escort_Tool")) {
            String s = redisUtil.get(address + "_Escort_Tool");
            if (code.equalsIgnoreCase(s)) {
                logger.warn("账号：" + address + ",验证码验证成功");
                m.put("code", 200);
                m.put("msg", "验证成功");
                m.put("success", true);
            } else {
                logger.error("账号：" + address + ",验证时验证码失败");
                m.put("code", 201);
                m.put("msg", "验证失败");
                m.put("success", false);
            }
        } else {
            logger.error("账号：" + address + ",验证时验证码失效");
            m.put("code", 201);
            m.put("msg", "验证码已失效");
            m.put("success", false);
        }
        return m;
    }
}
